<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Update API | ElasticSearch 7.7 权威指南中文版</title>
	<meta name="keywords" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <meta name="description" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
	<link rel="stylesheet" type="text/css" href="../static/styles.css" />
	<script>
	var _link = 'docs-update.html';
    </script>
</head>
<body>
<div class="main-container">
    <section id="content">
        <div class="content-wrapper">
            <section id="guide" lang="zh_cn">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                            <div style="color:gray; word-break: break-all; font-size:12px;">原英文版地址: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.7/docs-update.html" rel="nofollow" target="_blank">https://www.elastic.co/guide/en/elasticsearch/reference/7.7/docs-update.html</a>, 原文档版权归 www.elastic.co 所有<br/>本地英文版地址: <a href="../en/docs-update.html" rel="nofollow" target="_blank">../en/docs-update.html</a></div>
                        <!-- start body -->
                  <div class="page_header">
<strong>重要</strong>: 此版本不会发布额外的bug修复或文档更新。最新信息请参考 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html" rel="nofollow">当前版本文档</a>。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="rest-apis.html">REST APIs</a></span>
»
<span class="breadcrumb-link"><a href="docs.html">Document APIs</a></span>
»
<span class="breadcrumb-node">Update API</span>
</div>
<div class="navheader">
<span class="prev">
<a href="docs-delete-by-query.html">« Delete by query API</a>
</span>
<span class="next">
<a href="docs-update-by-query.html">Update by query API »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="docs-update"></a>Update API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h2>
</div></div></div>

<p>Updates a document using the specified script.</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="docs-update-api-request"></a>Request<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h3>
</div></div></div>
<p><code class="literal">POST /&lt;index&gt;/_update/&lt;_id&gt;</code></p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="update-api-desc"></a>Description<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h3>
</div></div></div>
<p>Enables you to script document updates. The script can update, delete, or skip
modifying the document. The update API also supports passing a partial document,
which is merged into the existing document. To fully replace an existing
document, use the <a class="xref" href="docs-index_.html" title="Index API"><code class="literal">index</code> API</a>.</p>
<p>This operation:</p>
<div class="olist orderedlist">
<ol class="orderedlist">
<li class="listitem">
Gets the document (collocated with the shard) from the index.
</li>
<li class="listitem">
Runs the specified script.
</li>
<li class="listitem">
Indexes the result.
</li>
</ol>
</div>
<p>The document must still be reindexed, but using <code class="literal">update</code> removes some network
roundtrips and reduces chances of version conflicts between the GET and the
index operation.</p>
<p>The <code class="literal">_source</code> field must be enabled to use <code class="literal">update</code>. In addition to <code class="literal">_source</code>,
you can access the following variables through the <code class="literal">ctx</code> map: <code class="literal">_index</code>,
<code class="literal">_type</code>, <code class="literal">_id</code>, <code class="literal">_version</code>, <code class="literal">_routing</code>, and <code class="literal">_now</code> (the current timestamp).</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="docs-update-api-path-params"></a>Path parameters<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">&lt;index&gt;</code>
</span>
</dt>
<dd>
(Required, string) Name of the target index. By default, the index is created
automatically if it doesn’t exist. For more information, see <a class="xref" href="docs-index_.html#index-creation" title="Create indices automatically">Create indices automatically</a>.
</dd>
<dt>
<span class="term">
<code class="literal">&lt;_id&gt;</code>
</span>
</dt>
<dd>
(Required, string) Unique identifier for the document to be updated.
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="docs-update-api-query-params"></a>Query parameters<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">if_seq_no</code>
</span>
</dt>
<dd>
(Optional, integer) Only perform the operation if the document has this
sequence number. See <a class="xref" href="docs-index_.html#optimistic-concurrency-control-index" title="Optimistic concurrency control">Optimistic concurrency control</a>.
</dd>
<dt>
<span class="term">
<code class="literal">if_primary_term</code>
</span>
</dt>
<dd>
(Optional, integer) Only perform the operation if the document has
this primary term. See <a class="xref" href="docs-index_.html#optimistic-concurrency-control-index" title="Optimistic concurrency control">Optimistic concurrency control</a>.
</dd>
<dt>
<span class="term">
<code class="literal">lang</code>
</span>
</dt>
<dd>
(Optional, string) The script language. Default: <code class="literal">painless</code>.
</dd>
<dt>
<span class="term">
<code class="literal">refresh</code>
</span>
</dt>
<dd>
(Optional, enum) If <code class="literal">true</code>, Elasticsearch refreshes the affected shards to make this
operation visible to search, if <code class="literal">wait_for</code> then wait for a refresh to make
this operation visible to search, if <code class="literal">false</code> do nothing with refreshes.
Valid values: <code class="literal">true</code>, <code class="literal">false</code>, <code class="literal">wait_for</code>. Default: <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">retry_on_conflict</code>
</span>
</dt>
<dd>
(Optional, integer) Specify how many times should the operation be retried when
 a conflict occurs. Default: 0.
</dd>
<dt>
<span class="term">
<code class="literal">routing</code>
</span>
</dt>
<dd>
(Optional, string) Target the specified primary shard.
</dd>
<dt>
<span class="term">
<code class="literal">_source</code>
</span>
</dt>
<dd>
(Optional, list) Set to <code class="literal">false</code> to disable source retrieval (default: <code class="literal">true</code>).
You can also specify a comma-separated list of the fields you want to retrieve.
</dd>
<dt>
<span class="term">
<code class="literal">_source_excludes</code>
</span>
</dt>
<dd>
(Optional, list) Specify the source fields you want to exclude.
</dd>
<dt>
<span class="term">
<code class="literal">_source_includes</code>
</span>
</dt>
<dd>
(Optional, list) Specify the source fields you want to retrieve.
</dd>
<dt>
<span class="term">
<code class="literal">master_timeout</code>
</span>
</dt>
<dd>
(Optional, <a class="xref" href="common-options.html#time-units" title="Time units">time units</a>) Specifies the period of time to wait for
a connection to the master node. If no response is received before the timeout
expires, the request fails and returns an error. Defaults to <code class="literal">30s</code>.
</dd>
<dt>
<span class="term">
<code class="literal">timeout</code>
</span>
</dt>
<dd>
(Optional, <a class="xref" href="common-options.html#time-units" title="Time units">time units</a>) Specifies the period of time to wait for
a response. If no response is received before the timeout expires, the request
fails and returns an error. Defaults to <code class="literal">30s</code>.
</dd>
<dt>
<span class="term">
<code class="literal">wait_for_active_shards</code>
</span>
</dt>
<dd>
<p>(Optional, string) The number of shard copies that must be active before
proceeding with the operation. Set to <code class="literal">all</code> or any positive integer up
to the total number of shards in the index (<code class="literal">number_of_replicas+1</code>).
Default: 1, the primary shard.</p>
<p>See <a class="xref" href="docs-index_.html#index-wait-for-active-shards" title="Active shards">Active shards</a>.</p>
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="update-api-example"></a>Examples<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h3>
</div></div></div>
<p>First, let’s index a simple doc:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT test/_doc/1
{
    "counter" : 1,
    "tags" : ["red"]
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1490.console"></div>
<p>To increment the counter, you can submit an update request with the
following script:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : {
        "source": "ctx._source.counter += params.count",
        "lang": "painless",
        "params" : {
            "count" : 4
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1491.console"></div>
<p>Similarly, you could use and update script to add a tag to the list of tags
(this is just a list, so the tag is added even it exists):</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : {
        "source": "ctx._source.tags.add(params.tag)",
        "lang": "painless",
        "params" : {
            "tag" : "blue"
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1492.console"></div>
<p>You could also remove a tag from the list of tags. The Painless
function to <code class="literal">remove</code> a tag takes the array index of the element
you want to remove. To avoid a possible runtime error, you first need to
make sure the tag exists. If the list contains duplicates of the tag, this
script just removes one occurrence.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : {
        "source": "if (ctx._source.tags.contains(params.tag)) { ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag)) }",
        "lang": "painless",
        "params" : {
            "tag" : "blue"
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1493.console"></div>
<p>You can also add and remove fields from a document. For example, this script
adds the field <code class="literal">new_field</code>:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : "ctx._source.new_field = 'value_of_new_field'"
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1494.console"></div>
<p>Conversely, this script removes the field <code class="literal">new_field</code>:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : "ctx._source.remove('new_field')"
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1495.console"></div>
<p>Instead of updating the document, you can also change the operation that is
executed from within the script.  For example, this request deletes the doc if
the <code class="literal">tags</code> field contains <code class="literal">green</code>, otherwise it does nothing (<code class="literal">noop</code>):</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : {
        "source": "if (ctx._source.tags.contains(params.tag)) { ctx.op = 'delete' } else { ctx.op = 'none' }",
        "lang": "painless",
        "params" : {
            "tag" : "green"
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1496.console"></div>
<h5>
<a id="_update_part_of_a_document"></a>Update part of a document<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h5>
<p>The following partial update adds a new field to the
existing document:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "doc" : {
        "name" : "new_name"
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1497.console"></div>
<p>If both <code class="literal">doc</code> and <code class="literal">script</code> are specified, then <code class="literal">doc</code> is ignored. If you
specify a scripted update, include the fields you want to update in the script.</p>
<h5>
<a id="_detect_noop_updates"></a>Detect noop updates<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h5>
<p>By default updates that don’t change anything detect that they don’t change
anything and return <code class="literal">"result": "noop"</code>:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "doc" : {
        "name" : "new_name"
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1498.console"></div>
<p>If the value of <code class="literal">name</code> is already <code class="literal">new_name</code>, the update
request is ignored and the <code class="literal">result</code> element in the response returns <code class="literal">noop</code>:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
   "_shards": {
        "total": 0,
        "successful": 0,
        "failed": 0
   },
   "_index": "test",
   "_type": "_doc",
   "_id": "1",
   "_version": 7,
   "_primary_term": 1,
   "_seq_no": 6,
   "result": "noop"
}</pre>
</div>
<p>You can disable this behavior by setting <code class="literal">"detect_noop": false</code>:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "doc" : {
        "name" : "new_name"
    },
    "detect_noop": false
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1499.console"></div>
<h5>
<a id="upserts"></a>Upsert<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h5>
<p>If the document does not already exist, the contents of the <code class="literal">upsert</code> element
are inserted as a new document.  If the document exists, the
<code class="literal">script</code> is executed:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "script" : {
        "source": "ctx._source.counter += params.count",
        "lang": "painless",
        "params" : {
            "count" : 4
        }
    },
    "upsert" : {
        "counter" : 1
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1500.console"></div>
<h5>
<a id="scripted_upsert"></a>Scripted upsert<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h5>
<p>To run the script whether or not the document exists, set <code class="literal">scripted_upsert</code> to
<code class="literal">true</code>:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST sessions/_update/dh3sgudg8gsrgl
{
    "scripted_upsert":true,
    "script" : {
        "id": "my_web_session_summariser",
        "params" : {
            "pageViewEvent" : {
                "url":"foo.com/bar",
                "response":404,
                "time":"2014-01-01 12:32"
            }
        }
    },
    "upsert" : {}
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1501.console"></div>
<h5>
<a id="doc_as_upsert"></a>Doc as upsert<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/docs/update.asciidoc">edit</a>
</h5>
<p>Instead of sending a partial <code class="literal">doc</code> plus an <code class="literal">upsert</code> doc, you can set
<code class="literal">doc_as_upsert</code> to <code class="literal">true</code> to use the contents of <code class="literal">doc</code> as the <code class="literal">upsert</code>
value:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST test/_update/1
{
    "doc" : {
        "name" : "new_name"
    },
    "doc_as_upsert" : true
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1502.console"></div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>Using <a class="xref" href="ingest.html" title="Ingest node">ingest pipelines</a> with <code class="literal">doc_as_upsert</code> is not supported.</p>
</div>
</div>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="docs-delete-by-query.html">« Delete by query API</a>
</span>
<span class="next">
<a href="docs-update-by-query.html">Update by query API »</a>
</span>
</div>
</div>

                  <!-- end body -->
                        </div>
                        <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                        
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </section>
</div>
<script src="../static/cn.js"></script>
</body>
</html>